<template>
  <div :key="tableKey">
    <el-table
    style="width: 100%"
      :data="element.componentProps.tableData"
      :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
      border
      row-key="id"
      ref="tableRef"
    >
      <el-table-column
        v-for="item in element.componentProps.columns"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
      />
    </el-table>
    <div style="margin-top: 20px;" v-if="element.componentProps.pagination">
      <el-pagination background layout="prev, pager, next" :total="0" />
    </div>
   
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  inject,
  nextTick,
  onBeforeUnmount,
  onMounted,
  ref,
  toRefs,
} from "vue";
import type { LowCodeImp, ComponentImp } from "@/components/low-code/core/type";
import Sortable from "sortablejs";
import { v4 as uuidv4 } from "uuid";

export default defineComponent({
  name: "tableWidget",
  props: ["element"],
  setup(props) {
    const getLowCodeInstance = inject("getLowCodeInstance") as Function;
    const lowCode = getLowCodeInstance() as LowCodeImp;
    const { element } = toRefs(props);
    const tableRef = ref();
    const tableKey = ref(uuidv4());
    let sortableInstance: any = null;
    const init = () => {
      nextTick(() => {
        if (sortableInstance) {
          sortableInstance.destroy();
          sortableInstance = null;
        }
        // 获取表格头元素
        const el = tableRef.value.$el.querySelectorAll(
          ".el-table__header-wrapper thead tr"
        )[0];
        // 初始化sortable
        sortableInstance = new Sortable(el, {
          animation: 180,
          delay: 0,
          onEnd: (evt: { oldIndex: string | number; newIndex: any }) => {
            // 列顺序变化后的处理
            const oldItem = element.value.componentProps.columns[evt.oldIndex];
            element.value.componentProps.columns.splice(evt.oldIndex, 1);
            element.value.componentProps.columns.splice(evt.newIndex, 0, oldItem);
            tableKey.value = uuidv4();
            init();
          },
        });
      });
    };

    onBeforeUnmount(() => {
      if (sortableInstance) {
        sortableInstance.destroy();
        sortableInstance = null;
      }
    });

    onMounted(() => {
      init();
    });

    return {
      element,
      tableRef,
      tableKey,
    };
  },
});
</script>

<style scoped>
 ::v-deep .el-table__empty-block{
  height: 300px !important;
}
</style>
